-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
59 lines (48 loc) · 1.75 KB
/
Solution.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import java.util.*;
public class CycleDetectionDirectedGraph {
static boolean detectCycleUtil(int v, boolean[] visited, boolean[] recStack, List<List<Integer>> graph) {
visited[v] = true;
recStack[v] = true;
for (int neighbor : graph.get(v)) {
if (!visited[neighbor] && detectCycleUtil(neighbor, visited, recStack, graph)) {
return true;
} else if (recStack[neighbor]) {
return true;
}
}
recStack[v] = false;
return false;
}
static boolean detectCycle(List<List<Integer>> graph, int vertices) {
boolean[] visited = new boolean[vertices];
boolean[] recStack = new boolean[vertices];
for (int i = 0; i < vertices; i++) {
if (!visited[i] && detectCycleUtil(i, visited, recStack, graph)) {
return true;
}
}
return false;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of vertices and edges: ");
int vertices = scanner.nextInt();
int edges = scanner.nextInt();
List<List<Integer>> graph = new ArrayList<>();
for (int i = 0; i < vertices; i++) {
graph.add(new ArrayList<>());
}
System.out.println("Enter the edges (u -> v):");
for (int i = 0; i < edges; i++) {
int u = scanner.nextInt();
int v = scanner.nextInt();
graph.get(u).add(v);
}
if (detectCycle(graph, vertices)) {
System.out.println("Cycle detected in the graph.");
} else {
System.out.println("No cycle detected in the graph.");
}
scanner.close();
}
}